package com.jit.monitor;

import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.Log;
import com.google.gson.Gson;
import com.jit.baselib.bean.response.BaseResponse;
import com.jit.baselib.ui.base.BaseObserver;
import com.jit.baselib.ui.base.ExceptionHandle;
import com.jit.monitor.base.ApiRetrofit;
import com.jit.monitor.commom.AppConstant;
import com.jit.monitor.model.bean.Extra_push;
import com.jit.monitor.ui.activity.MainActivity;
import com.jit.monitor.util.JPushHelper;
import com.orhanobut.logger.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Iterator;
import cn.jpush.android.api.JPushInterface;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 自定义接收器
 * 
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 *
 * 极光推送（JPush）是一个端到端的推送服务，使得服务器端消息能够及时地推送到终端用户手机上，
 * 让开发者积极地保持与用户的连接，从而提高用户活跃度、提高应用的留存率。
 *
 * JPush Android SDK 是作为 Android Service 长期运行在后台的，从而创建并保持长连接，保持永远在线的能力。
 * 目前测试只能打开铃声 并不能打开呼吸等啊
 * 广播接收器对象只在调用onReceive(上下文、意图)时有效。一旦代码从这个函数中返回，系统就会认为该对象已完成，不再活动。
 * 因此在该类中保存的变量信息只能在本次调用中被使用，不会保存到下一次调用。所以，想要在该类中保存变量，只能通过其他方式进行
 *
 * @author apple
 */
public class MyReceiver extends BroadcastReceiver {
	private static final String TAG = "JPUSH";
	private static final int LEAST_RECEIVE_TIME = 30*1000;
	private Context mContext;
	private NotificationManager mNotificationManager;

	@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
	@Override
	public void onReceive(Context context, Intent intent) {
		this.mContext = context;
		if (null != intent) {
			Bundle bundle = intent.getExtras();
			if (null == bundle){
				return;
			}
			// 整个的信息-----
			// Logger.e(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));
			if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
				Logger.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
			} else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
				Log.e(TAG, "onReceive: 接收到推送下来的通知");
				// 接受到通知时 进行设定-----
				int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
				Log.e(TAG, "onReceive: "+notifactionId+" 时间 = "+System.currentTimeMillis()+"  接收时间 = "+ JPushHelper.getInstance().getCurrentTime());
				// 每隔30秒收到一次其他的进行过滤
				// 接受到通知有铃声
				if (System.currentTimeMillis() - JPushHelper.getInstance().getCurrentTime() >= LEAST_RECEIVE_TIME){
					Log.e(TAG, "----间隔超过了2分钟----" );
					JPushHelper.getInstance().setCurrentTime( System.currentTimeMillis());
					Log.e(TAG, "设置时间 = "+JPushHelper.getInstance().getCurrentTime() );
					for (String key : bundle.keySet()) {
						if (key.equals(JPushInterface.EXTRA_ALERT_TYPE)) {
							String type = bundle.getString(key);
							if ("1".equals(type)) {
								Logger.d(TAG, "----播放铃声----");
								try {
									defaultMediaPlayer(context);
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
						}else if (key.equals(JPushInterface.EXTRA_EXTRA)){
							Extra_push push = new Gson().fromJson(bundle.getString(JPushInterface.EXTRA_EXTRA), Extra_push.class);
							if (null != push){
								openLedByCameraID(push.getCameraId());
							}
						}
					}

					onSendBroadcast(context, bundle);
				}else {
					cleanNotificationByID(notifactionId);
				}


			} else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
				Logger.d(TAG, "[MyReceiver] 用户点击打开了通知");
				onNotificationClick(context,bundle);
			} else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
				Logger.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
				//在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..
			} else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
				boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
				Logger.w(TAG, "[MyReceiver]" + intent.getAction() + " connected state change to " + connected);
			} else {
				Logger.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
			}
		}
	}

	private void cleanNotificationByID(int ID){
		if (null == mNotificationManager) {
			mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
		}
		assert mNotificationManager != null;
		mNotificationManager.cancel(ID);
	}

	private void openLedByCameraID(String cameraID){
		ApiRetrofit.getInstance().controlLedState(cameraID, AppConstant.NOTIFY_WITH_LED_ON)
				.subscribeOn(Schedulers.io())
				.observeOn(AndroidSchedulers.mainThread())
				.subscribe(new BaseObserver<BaseResponse>() {
					@Override
					public void onNext(BaseResponse baseResponse) {

					}

					@Override
					public void onError(ExceptionHandle.ResponseException exception) {

					}
				});
	}

	private String printBundle(Bundle bundle) {
		StringBuilder sb = new StringBuilder();
		for (String key : bundle.keySet()) {
			if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
				sb.append("\nkey:").append(key).append(", value:").append(bundle.getInt(key));
			}else if(key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)){
				sb.append("\nkey:").append(key).append(", value:").append(bundle.getBoolean(key));
			} else if (key.equals(JPushInterface.EXTRA_ALERT_TYPE)){
				sb.append("\nkey:").append(key).append(", value:").append(bundle.getString(key));

			}else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
				if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
					Logger.i(TAG, "This message has no Extra data");
					continue;
				}
				try {
					JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
					Iterator<String> it =  json.keys();

					while (it.hasNext()) {
						String myKey = it.next();
						sb.append("\nkey:").append(key).append(", value: [").append(myKey).append(" - ").append(json.optString(myKey)).append("]");
					}
				} catch (JSONException e) {
					Logger.e(TAG, "Get message extra JSON error!");
				}
			} else {
				sb.append("\nkey:").append(key).append(", value:").append(bundle.get(key));
			}
		}
		return sb.toString();
	}


    /**
     * 打开了通知-----
     * @param context
     * @param bundle
     */
    private void onNotificationClick(Context context, Bundle bundle) {
        if (bundle != null) {
            String alert = bundle.getString(JPushInterface.EXTRA_ALERT, "");
            if (alert == null || alert.length() == 0) {
                alert = bundle.getString(JPushInterface.EXTRA_MESSAGE, "");
            }
            String action = bundle.getString(JPushInterface.EXTRA_EXTRA, "");
            Log.e(TAG, "[MyReceiver] action 1 :" + action);
			try {
				Intent intent = new Intent(context, MainActivity.class);
				intent.putExtra("alert", alert);
				intent.putExtra("action", action);
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
                Log.e(TAG, "onNotificationClick:-------执行了啊" );
				context.getApplicationContext().startActivity(intent);
			} catch (Exception e) {
			}
        }
    }

    /**
     * 发送广播通知-------
     * @param context
     * @param bundle
     */
    private void onSendBroadcast(Context context, Bundle bundle) {
		Intent bintent = new Intent();
		bintent.putExtras(bundle);
		bintent.setAction("com.jit.monitor.refreshUI");
		context.sendBroadcast(bintent);
    }

	/**
	 * 播放系统默认提示音 ---------- 当接受到消息时 进行设置
	 *
	 * ALERT_TYPE = 4
	 * @return MediaPlayer对象
	 * @throws Exception
	 */
	public void defaultMediaPlayer(Context mContext) throws Exception {
		Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
		Ringtone r = RingtoneManager.getRingtone(mContext, notification);
		r.play();
	}
}
